package com.adu.music.spider;

import com.adu.music.parser.ArtistParser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2017/1/1
 */
public class MvNewSpider extends AbstractSpider {

    private int pageIndex = 0;
    private final int pageSize = 100;

    @Override
    protected void initTaskQueue() {
        List<Map<String, Object>> artistes = queryArtistsByIndex(pageIndex);
        artistes.forEach(artist -> putTaskToQueue(artist.get("id")));
        pageIndex++;
    }

    private List<Map<String, Object>> queryArtistsByIndex(int index) {
        final String sql = "select id FROM artist LIMIT :offset,:size;";
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("offset", index * pageSize);
        paramMap.put("size", pageSize);
        return asyncNamedParameterJdbcTemplate.queryForList(sql, paramMap);
    }

    @Override
    protected void produceTask() {
        while (!Thread.interrupted()) {
            List<Map<String, Object>> artistes = queryArtistsByIndex(pageIndex);
            artistes.forEach(artist -> putTaskToQueue(artist.get("id")));
            if (artistes.size() < pageSize) break;
            pageIndex++;
        }
    }

    @Override
    protected void consumeTask(Object task) {
        final String sql = "insert into mv(id,name,song_id,artist_id,artist_name,comment) values(:id,:name,:song_id,:artist_id,:artist_name,:comment) " +
                "ON DUPLICATE KEY UPDATE comment=values(comment),updated_at=now()";
        String artistId = String.valueOf(task);
        List<Map<String, Object>> result = ArtistParser.parseTop50Mvs(artistId);
        result.forEach(map -> asyncNamedParameterJdbcTemplate.update(sql, map));
    }
}
